﻿using Orchard;
using Orchard.Environment.Extensions;
using Orchard.Localization;
using Orchard.Localization.Models;
using Orchard.Localization.Services;
using Orchard.Projections.Descriptors.Filter;
using IFilterProvider = Orchard.Projections.Services.IFilterProvider;

namespace Vitus.Localization.Projections
{
    [OrchardFeature("Vitus.CultureProjectionFilters")]
    public class CurrentCultureFilter : IFilterProvider
    {
        private readonly IWorkContextAccessor _workContextAccessor;
        private readonly ICultureManager _cultureManager;

        public CurrentCultureFilter(
            IWorkContextAccessor workContextAccessor,
            ICultureManager cultureManager)
        {
            _workContextAccessor = workContextAccessor;
            _cultureManager = cultureManager;
            T = NullLocalizer.Instance;
        }

        public Localizer T { get; set; }

        public void Describe(DescribeFilterContext describe)
        {
            describe.For("Localization", T("Localization"), T("Localization"))
                .Element("CurrentCulture", T("Current culture"), T("Current culture localizations"),
                         ApplyFilter,
                         DisplayFilter,
                         null
                );
        }

        public void ApplyFilter(FilterContext context)
        {
            string currentCulture = _workContextAccessor.GetContext().CurrentCulture;
            int currentCultureId = _cultureManager.GetCultureByName(currentCulture).Id;

            context.Query = context.Query.Where(
                x => x.ContentPartRecord<LocalizationPartRecord>(),
                x => x.Eq("CultureId", currentCultureId));
        }

        public LocalizedString DisplayFilter(FilterContext context)
        {
            return T("Content localizations of the current culture");
        }
    }
}